package vip.meeet.mysql.helper;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class MySQLSSHHelper {

    public static void main(final String[] args) throws SQLException {
        final int lport = 3306;
        final String host = "118.144.66.174";
        final String rhost = "192.168.8.254";
        final int dbport = 3306;
        final String hostUser = "xx";
        final String dbuserName = "xx";
        final String dbpassword = "xxx";
        final String dburl = "jdbc:mysql://localhost:" + dbport  + "/information_schema?useUnicode=true&characterEncoding=UTF-8";
        final String driverName = "com.mysql.jdbc.Driver";
        Session session = null;
        Connection dbConn = null;
        try {
            final JSch jsch = new JSch();
            session = jsch.getSession(hostUser, host, 10022);
            UserInfo userInfo = new JschUserInfo("xxx");

            session.setUserInfo(userInfo);
            session.connect();
            System.out.println("Connected");
            final int assinged_port = session.setPortForwardingL(lport, rhost, dbport);
            System.out.println("localhost:" + assinged_port + " -> " + rhost + ":" + dbport);
            System.out.println("Port Forwarded");

            //mysql database connectivity
            Class.forName(driverName).newInstance();
            dbConn = DriverManager.getConnection(dburl, dbuserName, dbpassword);

            System.out.println("Database connection established");
            System.out.println("DONE");

        } catch (final Exception e) {
            e.printStackTrace();
        } finally {
            if (dbConn != null && !dbConn.isClosed()) {
                System.out.println("Closing Database Connection");
                dbConn.close();
            }
            if (session != null && session.isConnected()) {
                System.out.println("Closing SSH Connection");
                session.disconnect();
            }
        }
    }


}
